package com.gljx.web.controller;

import com.gljx.util.CommonExport;
import com.gljx.util.GetFid;
import com.gljx.util.GetFnumber;
import com.gljx.util.TimeFormat;
import com.gljx.web.Entity.Department;
import com.gljx.web.Entity.PageBean;
import com.gljx.web.Entity.Remuneration;
import com.gljx.web.Entity.User;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import com.gljx.web.service.RemunerationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping("/")
public class RemunerationController {
	
	// 自动注入
	@Autowired
	private DepartmentService departmentService;

	@Autowired
	private CustomLogService customLogService;

	@Autowired
	private RemunerationService remunerationService;
	
	/**
	 * 默认查找全部薪酬信息
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/selectRemuneration.html/look.action")
	public String selRemuneration(HttpServletRequest request,@RequestParam(value = "type",defaultValue = "") String type)throws Exception{
		PageBean<Remuneration> pb=new PageBean<Remuneration>();
		//获取session中的登录信息
        User user = (User) request.getSession().getAttribute("user");
        try {
			//获取分页
			pb = getPageBean(request,user.getFcompanyid());
			//获取当前分页的值
			List<Remuneration> remunerationList = pb.getBeanList();
			//把获取到的数据传回页面
			request.setAttribute("remunerationList", remunerationList);
			request.setAttribute("pb", pb);
			request.setAttribute("type",type);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       /* List<Remuneration> remunerationList=null;
        remunerationList=remunerationService.selectRemunerationList(user.getFcompanyid());
        request.setAttribute("remunerationList", remunerationList);*/
		return "backHome/basicData/humanResourceData/remuneration/remunerationList";
	}
	@RequestMapping(value="/selectRemunerationByFnameL2.html")
	public String sqlRemuneration(HttpServletRequest request,String fnameL2)throws Exception{
		//获取操作人信息
	    User user = (User)request.getSession().getAttribute("user");
	    if(fnameL2.equals("")){//如果需要查询的名字为空则默认进入查询全部信息
	    	selRemuneration(request,null);
	    }else {
	    	fnameL2.trim();//去空格
	    	PageBean<Remuneration> pb=new PageBean<>();
			//List<Remuneration> cars = carService.queryCarByFnumber(fnumber,user.getFcompanyid());
	    	List<Remuneration> remunerationList=remunerationService.selectRemunerationByFname(fnameL2, user.getFcompanyid());
			//总记录数
			pb.setTr(remunerationList.size());
			//每页记录数
			pb.setPs(50);
			//把数据传到页面上
			request.setAttribute("pb", pb);
			request.setAttribute("remunerationList", remunerationList);
			request.setAttribute("fnameL2", fnameL2);
	    }
		return "backHome/basicData/humanResourceData/remuneration/remunerationList";
	}
	/**
	 * 跳转至新增薪酬项目页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/intoAddRemuneration.html")
	public String intoAddRemuneration(HttpServletRequest request,String type)throws Exception{
		//获取操作人信息
	    User user = (User)request.getSession().getAttribute("user");
	    //获取部门
	    List<Department>departments = departmentService.queryAdminByController(user.getFcompanyid());
	    //获取组织
	    Department department = departmentService.queryAdminByFid(user.getFcompanyid());
	  //获取上一个编码
        /* String number = remunerationService.selectFnumber(user.getFcompanyid());*/
        //获取编码
        String fnumber = GetFnumber.fnumbers("SFRT");
	    request.setAttribute("department_remuneration", department);
	    request.setAttribute("departments_remuneration", departments);
	    request.setAttribute("fnumber", fnumber);
	    request.setAttribute("type",type);
		return "backHome/basicData/humanResourceData/remuneration/addRemuneration";
	}
	/**
	 * 增加薪酬项目
	 * @param request
	 * @param remuneration
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/addRemuneration.html")
	public String addRemuneraction(HttpServletRequest request,Remuneration remuneration)throws Exception{
		//获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        /*获取当前时间*/
        String createTime = TimeFormat.timeFormat(new Date());
        /*获取uuid*/
        remuneration.setFid(GetFid.UUIDIntoFid());
        remuneration.setCfficompanyid(user.getFcompanyid());
        remuneration.setFcreatorid(user.getFid());
        remuneration.setFcreatetime(createTime);
        remuneration.setFcontrolunitid(user.getFcompanyid());
        remuneration.setCreateName(user.getName());
        //增加薪酬项目信息
        int row = remunerationService.addRemuneration(remuneration);
        String result ="";
        if(row > 0){
        	result ="1";
		}
        customLogService.addLog("人力资源基础资料", createTime + "对薪酬项目进行操作", null, user.getFid());
		return "redirect:/DrivingSys/intoAddRemuneration.html?type="+result;
	}
	
	/**
	 * 跳转到修改薪酬信息页面
	 * @param request
	 * @param fid 通过fid把被选中的薪酬信息带到修改页面中去
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="intoUpdateRemuneration.html")
	public String intoUpdateRemuneration(HttpServletRequest request,
			@RequestParam(value="fid",required=false) String fid)throws Exception{
		// 获取当前登录人的信息
		User user = (User) request.getSession().getAttribute("user");
		// 根据fid查询单条扣款项目信息带到修改页面中去
		Remuneration remuneration=null;
		if(fid !=null && !fid.equals("")){
			remuneration=remunerationService.selectByPrimaryKey(fid);
		}
		//获取部门
	    List<Department>departments = departmentService.queryAdminByController(user.getFcompanyid());
	    //获取组织
	    Department department = departmentService.queryAdminByFid(user.getFcompanyid());
	    request.setAttribute("department_remuneration", department);
	    request.setAttribute("departments_remuneration", departments);
	    request.setAttribute("update_remuneration", remuneration);
		return "backHome/basicData/humanResourceData/remuneration/updateRemuneration";
	}
	
	/**
	 * 修改薪酬项目信息
	 * @param request
	 * @param remuneration 需要修改的内容
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/updateRemuneration.html")
	public String updateRemuneration(HttpServletRequest request,Remuneration remuneration)throws Exception{
		//获取当前登录人的信息
		User user = (User) request.getSession().getAttribute("user");
		//公司id
		remuneration.setCfficompanyid(user.getFcompanyid());
	    //控制单元id
		remuneration.setFcontrolunitid(user.getFcompanyid());
		//获取当前修改时间
		String updateTime = TimeFormat.timeFormat(new Date());
		//设置最后修改时间
		remuneration.setFlastupdatetime(updateTime);
		 //设置修改人id
		remuneration.setFlastupdateuserid(user.getFid());
		//修改
		int row = remunerationService.updateRemuneration(remuneration);
		String result ="";
		if( row > 0){
			result= "1";
		}
		//添加日志
		customLogService.addLog("人力资源基础资料", TimeFormat.timeFormat(new Date()) + "对薪酬项目进行更新", null, user.getFid());
		return "redirect:/DrivingSys/selectRemuneration.html/look.action?type="+result;
	}
	/**
	 * 根据fid删除薪酬项目信息
	 * @param request
	 * @param deleteId 需要删除的fid数组
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteRemunerationByFid.html")
	public String deleteRemunerationByFid(HttpServletRequest request, String[] deleteId,String fid)throws Exception{
		User user = (User) request.getSession().getAttribute("user");
        //删除记录
		if (fid == null || "".equals(fid)) {
			for (int i = 0; i < deleteId.length; i++) {
				/* 过滤为空的删除操作 */
				if (!deleteId[i].equals("") && deleteId[i] != null) {
					remunerationService.deleteRemunerationByFid(deleteId[i]);
				}
			}
		} else {
			remunerationService.deleteRemunerationByFid(fid);
		}
        
        //添加日志
        customLogService.addLog("人力资源基础资料", TimeFormat.timeFormat(new Date()) + "对薪酬项目进行删除", null, user.getFid());
		return "redirect:/DrivingSys/selectRemuneration.html/look.action";
		
	}
	
	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
	public PageBean<Remuneration> getPageBean(HttpServletRequest request,String companyId) throws Exception
	{

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("SELECT R .FID, R .FNUMBER, R .FNAME_L2, R .FSIMPLENAME, R .FDESCRIPTION_L2, R .CFSTATE, R .CFFIXATION, R.CFAMOUNT, e.name as createName,");
        psql.append("u.name as updateName, TO_CHAR (R .FCREATETIME, 'yyyy-MM-dd HH:mi:ss') fcreatetime,TO_CHAR (R .FLASTUPDATETIME,'yyyy-MM-dd HH:mi:ss') flastupdatetime ");
		psql.append("FROM CT_DS_REMUNERATIONITEM R LEFT JOIN T_E_USER e on R .FCREATORID=e.fid LEFT JOIN T_E_USER u  on R.FLASTUPDATEUSERID=u.fid where R.FCONTROLUNITID='"+companyId+"'");
		psql.append("ORDER BY R .FCREATETIME DESC");
		int psize=15; //每页显示数
		int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= remunerationService.selectPage(pindex, psql.toString(), psize);
		PageBean<Remuneration> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<Remuneration>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}

	/**
	 * 取记录总数  
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception
	{

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=remunerationService.selectPageCount(psql);
		return paramMap;		
	}

	/**
	 * 导出 基础资料 薪酬项目
	 * @param response
	 * @param request
	 * @param fnameL2
	 */
	@RequestMapping(value = "/importRemuneration")
	public void importRemuneration(HttpServletResponse response, HttpServletRequest request, String fnameL2){
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//定义接收类型
		List<Object> data = new ArrayList<>();
		//查询数据
		List<Remuneration> remunerations =remunerationService.selectRemunerationByFname(fnameL2,user.getFcompanyid());
		for (Remuneration remuneration :remunerations){
			data.add(remuneration.getFnumber());
			data.add(remuneration.getFnameL2());
			data.add(remuneration.getFsimplename());
			data.add(remuneration.getFdescriptionL2());
			data.add(remuneration.getFcreatetime());
			data.add(remuneration.getFlastupdatetime());
			data.add(remuneration.getCreateName());
			data.add(remuneration.getUpdateName());
			if(remuneration.getCfstate() == null){
				data.add(null);
			}else if(remuneration.getCfstate().compareTo(1L) == 0){
				data.add("启动");
			}else{
				data.add("禁用");
			}
			if(remuneration.getCffixation() == null){
				data.add(null);
			}else if(remuneration.getCffixation().compareTo(1L) == 0){
				data.add("固定");
			}else if(remuneration.getCffixation().compareTo(2L) == 0){
				data.add("可变");
			}else if(remuneration.getCffixation().compareTo(3L) == 0){
				data.add("手录");
			}else{
				data.add("内置");
			}
			data.add(remuneration.getCfamount());
		}
		//头部数据
		String head[] = {"编码", "名称", "简称", "描述", "创建时间", "最后修改时间", "创建者", "修改人","状态","类型","金额"};
		//长度
		Integer length[] = {9000, 5000, 5000, 5000, 5000, 5000, 3000, 3000,3000,3000,3000};
		try {
			//导出Excel
			CommonExport.importExcel(response, "薪酬项目" + TimeFormat.getNowTime2() + ".xls", "薪酬项目", data, head, length);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
